package com.itfreer.data.metadata;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

import com.itfreer.data.metadata.dao.DefaultDictionaryDao;
import com.itfreer.data.metadata.dao.DictionaryDirectoryDao;
import com.itfreer.data.metadata.entity.DataDictionaryDirectoryEntity;
import com.itfreer.data.metadata.entity.DataDictionaryEntity;
import com.itfreer.form.api.BaseDao;
import com.itfreer.form.api.DictionaryServiceImp;
import com.itfreer.form.api.dictionary.DictionaryEntity;

/**
 * 数据字典目录
 */
@Component("DictionaryDirectoryServiceImp")
public class DictionaryDirectoryServiceImp extends DictionaryServiceImp<DataDictionaryDirectoryEntity>
		implements DictionaryDirectoryService {

	@Autowired(required = false)
	private DictionaryDirectoryDao metadataNamesDao;
	@Autowired(required = false)
	private DefaultDictionaryDao dictionaryDao;

	@Override
	protected BaseDao<DataDictionaryDirectoryEntity> getDao() {
		return metadataNamesDao;
	}

	@Override
	public String getDictionaryName() {
		return "f_dictionary_directory";
	}

	/**
	 * 是否为租户间共享实体对象
	 */
	protected boolean isShareTenant() {
		return true;
	}

	/**
	 * 获取租户间共享字段名称 用于SAAS下数据管理
	 */
	protected String getShareTenantFieldName() {
		return "shareTenantID";
	}

	@Override
	protected DictionaryEntity convert(DataDictionaryDirectoryEntity t) {
		DictionaryEntity toEntity = new DictionaryEntity();
		BeanUtils.copyProperties(t, toEntity, "directoryType");
		if (t.getDirectoryType() == null || t.getDirectoryType().trim().equals("")
				|| t.getDirectoryType().trim().equals("1")) {
			toEntity.setLeaf(false);
		} else if (t.getDirectoryType().trim().equals("2") || t.getDirectoryType().trim().equals("3")) {
			toEntity.setLeaf(true);
		} else {
			toEntity.setLeaf(false);
		}
		toEntity.setInfo(t.getDirectoryType());
		return toEntity;
	}

	@Override
	protected String getDictionaryFields() {
		return "*";
	}

	/**
	 * 是否是树表
	 */
	protected boolean isTree() {
		return true;
	}

	/**
	 * 树的PID字段名
	 */
	protected String getTreePIDFieldName() {
		return "pid";
	}

	@Override
	public Boolean delete(String id) {
		// 配置事务策略
		DefaultTransactionDefinition def = new DefaultTransactionDefinition();
		def.setName("planOne-transaction");
		def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
		// 设置状态点
		TransactionStatus status = transactionManager.getTransaction(def);
		Boolean result = false;
		try {
			result = super.delete(id);
			// 删除字典服务
			Map<String, Object> where = new HashMap<>();
			where.put("dicName", id);
			dictionaryDao.deletes(where);
		} catch (Exception e) {
			transactionManager.rollback(status);
			throw e;
		}
		transactionManager.commit(status);
		return result;
	}

	@Override
	public DataDictionaryDirectoryEntity update(DataDictionaryDirectoryEntity entity) {
		// 配置事务策略
		DefaultTransactionDefinition def = new DefaultTransactionDefinition();
		def.setName("planOne-transaction");
		def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
		// 设置状态点
		TransactionStatus status = transactionManager.getTransaction(def);
		DataDictionaryDirectoryEntity result = null;
		try {
			result = super.update(entity);

			Map<String, Object> where = new HashMap<>();
			where.put("dicName", entity.getId());
			List<DataDictionaryEntity> list = dictionaryDao.getEntitys(where, null);
			for (DataDictionaryEntity item : list) {
				item.setShareTenantID(entity.getShareTenantID());
			}
			dictionaryDao.updateAll(list);
		} catch (Exception e) {
			transactionManager.rollback(status);
			throw e;
		}
		transactionManager.commit(status);
		return result;
	}

	/**
	 * 共享
	 * 
	 * @param id
	 * @param shareTenantID
	 * @param shareTenantName
	 * @return
	 */
	public Boolean share(String id, String shareTenantID, String shareTenantName) {
		Boolean result = updateShare(id, shareTenantID, shareTenantName);
		if (isTree()) {
			List<String> guids = getTreeChilds(this.getTreePIDFieldName(), id);
			for (String item : guids) {
				updateShare(item, shareTenantID, shareTenantName);
			}
		}
		return result;
	}

	private boolean updateShare(String id, String shareTenantID, String shareTenantName) {
		DataDictionaryDirectoryEntity entity = getEntity(id);
		if (entity == null) {
			return false;
		}
		if (entity.getShareTenantID() == null || entity.getShareTenantID().equals("")) {
			entity.setShareTenantID("," + shareTenantID + ",");
		} else {
			if (entity.getShareTenantID().indexOf("," + shareTenantID + ",") == -1) {
				entity.setShareTenantID(entity.getShareTenantID() + shareTenantID + ",");
			}
		}
		if (entity.getShareTenantName() == null || entity.getShareTenantName().equals("")) {
			entity.setShareTenantName("," + shareTenantName + ",");
		} else {
			if (entity.getShareTenantName().indexOf("," + shareTenantName + ",") == -1) {
				entity.setShareTenantName(entity.getShareTenantName() + shareTenantName + ",");
			}
		}
		update(entity);
		return true;
	}
}